/*
Copyright 2010 Christian Dadswell
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package subscriber.chrisdadswell.co.uk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

public class Activity_FindFeed extends Activity {

	public static final String _APP_TAG = "Activity_FindFeed";
	static Context context;
	public static String _WEB_URL = null;
	public static String _FEED_URL = null;
	public static String _FEED_TITLE = null;
	protected static final int DIALOG_FEEDLIST = 0;
	protected static final int DIALOG_TAGLIST = 1;
	protected static final int DIALOG_CONFIRMATION = 2;
	private FindFeedTask ffTask = null;
	
	// LIFECYCLES
	public void onStart() {
		super.onStart();
		Log.d(_APP_TAG, "---------- onStart");				
	} // END OF ONSTART
	
	public void onRestart() {
		super.onRestart();
		Log.d(_APP_TAG, "---------- onRestart");
	}
	public void onResume() {
		super.onResume();
		Log.d(_APP_TAG, "---------- onResume");
	} 
	public void onPause() {
		super.onPause();
		Log.d(_APP_TAG, "---------- onPause");
		Log.d(_APP_TAG, "---------- FIRE IN THE HOLE!");
		finish();
	}
	public void onStop() {
		super.onStop();
		Log.d(_APP_TAG, "---------- onStop");
	}	
	public void onDestroy() {
		super.onDestroy();
		Log.d(_APP_TAG, "---------- onDestroy");
		_FEED_URL = null;
		_WEB_URL = null;
		Log.d(_APP_TAG, "VAR: FeedURL = " + _FEED_URL + " WebURL = " + _WEB_URL);
		Log.d(_APP_TAG, "LIFECYCLE: Finish Activity_FindFeed ...");
	}
	
// SITE OR FEED
	public boolean SiteorFeed(String IntentString) { // SITE = true, FEED = false	
		Log.d(_APP_TAG, "METHOD: SiteorFeed (" + IntentString + ")");
		if(Func_Strings.FindWordInString(IntentString, ".xml")) {
			return false;
		}else if(Func_Strings.FindWordInString(IntentString, ".rdf")) {
			return false;
		}else if(Func_Strings.FindWordInString(IntentString, ".atom")) {
			return false;
		}
		return true;
	}

	// CREATE THE ACTIVITY
    @Override
    public void onCreate(Bundle savedInstanceState) { 
    	super.onCreate(savedInstanceState); 
		Log.d(_APP_TAG, "ACTIVITY: OnCreate");
		setContentView(R.layout.findfeed);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		context = this;
		ffTask = (FindFeedTask) getLastNonConfigurationInstance();
		
		Intent intent = getIntent();
		_WEB_URL = intent.getStringExtra(Intent.EXTRA_TEXT);
		Log.d(_APP_TAG, "VAR: WebURL = " + _WEB_URL);
		if(SiteorFeed(_WEB_URL)) {
    		Log.d(_APP_TAG, "RESPONSE: Site detected");
    		Log.d(_APP_TAG, "CALLING: FindFeedTask ...");

    		if (ffTask==null) {
    			ffTask = new FindFeedTask(this);
    			ffTask.execute(_WEB_URL);
    		} else {
    			ffTask.attach(this);
    		}

		}else{
    		// FEED URL NEEDS TO BE SET
    		Log.d(_APP_TAG, "RESPONSE: Feed detected");
    		Log.d(_APP_TAG, "VAR: FeedURL = " + _FEED_URL + " WebURL = " + _WEB_URL);
    		_FEED_URL = _WEB_URL;
        	// PASS FEED TITLE AND URL TO ACTIVITY_SUBSCRIBER
			Intent intentSubscribe = new Intent();
			Log.d(_APP_TAG, "ACTION: Bundling extras to send");
			intentSubscribe.setClass(context, Activity_Subscriber.class);
			intentSubscribe.putExtra("SelectedFeedTitle", "<No Title Set>");
			intentSubscribe.putExtra("SelectedFeedURL", _FEED_URL);
		    startActivity(intentSubscribe);
    	}
    }
    
	@Override
	public Object onRetainNonConfigurationInstance() {
		ffTask.detach();
		return(ffTask);
	}
    
    static class FindFeedTask extends AsyncTask<String, Void, Boolean> {
    	private ProgressDialog PD = new ProgressDialog(context);
    	Activity_FindFeed activity=null;
    	
    	FindFeedTask(Activity_FindFeed activity) {
			attach(activity);
		}
    	
    	protected void onPreExecute() {
    		PD.setMessage("\n\nSearching for feeds on\n" + _WEB_URL + "\n\n");
    		PD.show();
    	}
    	
    	@Override
		protected Boolean doInBackground(String... params) {
			Log.d(_APP_TAG, "doInBackground()");
			boolean _RESULT_FEED_FOUND = Func_HTTP.FindFeeds(_WEB_URL);
			return _RESULT_FEED_FOUND;
		}
    	
		@Override
		protected void onProgressUpdate(Void... unused) {
		}
		
		@Override
		protected void onPostExecute(Boolean _RESULT_FEED_FOUND) {
			if(_RESULT_FEED_FOUND) {
				activity.showDialog(DIALOG_FEEDLIST);
				if (PD.isShowing()) {
					PD.dismiss();
				}
			}else{
				Toast.makeText(context, "\nNo feeds found at adddress " + _WEB_URL + "\n", Toast.LENGTH_SHORT).show();
				PD.dismiss();
				activity.finish();
			}
		}
		
		void detach() {
			activity=null;
		}

		void attach(Activity_FindFeed activity) {
			this.activity=activity;
		}
    }
    
 // FEED LIST DIALOG
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog;
    	switch (id) {
        case DIALOG_FEEDLIST:
        	_FEED_URL = null;
        	Log.d(_APP_TAG, "DIALOG: Display Feed List");
        	final String[] _FEED_TITLES  = Func_HTTP.GetFeedHashKeys();
        	AlertDialog.Builder feeds_dialog = new AlertDialog.Builder(context);
            feeds_dialog.setTitle("Available feeds");
            feeds_dialog.setItems(_FEED_TITLES, new DialogInterface.OnClickListener() {
            	public void onClick(DialogInterface dialog, int which) {
                	_FEED_URL = Func_HTTP.GetFeedHashValue(_FEED_TITLES[which]);
                	Log.d(_APP_TAG, "Sending Feed URL - " + _FEED_URL);
                	_FEED_TITLE = _FEED_TITLES[which];
                	Log.d(_APP_TAG, "Sending Feed Title -" + _FEED_TITLE);
                	
                	// PASS FEED TITLE AND URL TO ACTIVITY_SUBSCRIBER
        			Intent intentSubscribe = new Intent();
        			Log.d(_APP_TAG, "ACTION: Bundling extras to send");
        			intentSubscribe.setClass(context, Activity_Subscriber.class);
        			intentSubscribe.putExtra("SelectedFeedTitle", _FEED_TITLE);
        			intentSubscribe.putExtra("SelectedFeedURL", _FEED_URL);
        		    startActivity(intentSubscribe);
        		    Log.d(_APP_TAG, "ACTION: Dismissing dialog");
                	dialog.dismiss();
        			return;
                }
            }                       
            );
            
            feeds_dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					Log.d(_APP_TAG, "ACTION: I've been cancelled!");
					finish();
				}
			});
            
            AlertDialog feeds_alert = feeds_dialog.create();
            return feeds_alert;
        default:
        	dialog = null;
    	}
		return super.onCreateDialog(id);
    }

    
}// END OF CLASS
